<template>
  <div>
    <TopFilter :list="topFilterList" :cols="3" :collapse="false" @filterChange="changeHandler" />
    <FilterTable
      ref="table"
      columnsRef="jzyCardType"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'rows'"
      :onRowSelectChange="rowSelectHandle"
      :onColumnsChange="columns => (this.columns = columns)"
    >
      <!-- <template slot="moreActions">
        <span @click="removeRecordHandle">删除数据</span>
      </template>-->
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-printer" @click="printBalanceClick">合并打印结算单</el-button>

        <el-button size="small" type="primary" icon="el-icon-printer" @click="printCard">打印出门证</el-button>
      </template>
    </FilterTable>
    <BasePrint ref="printVehicled" :data="this.printExitCardList" template="templateExitCard" />

    <!-- 打印结算单 -->
    <BasePrint ref="print" :data="printList" template="repair/repairReception/feesSettlement/mergeFinalStatementTemplate" />
    <!-- 结算单江苏 -->
    <!-- <BasePrint ref="printJS" :data="printList" template="repair/repairReception/feesSettlement/finalStatementTemplateJS" /> -->
    <!-- 结算单上海 -->
    <!-- <BasePrint ref="printSH" :data="printList" template="repair/repairReception/feesSettlement/finalStatementTemplateSH" /> -->
  </div>
</template>

<script>
// 数据字典/按钮权限
import moment from 'moment';
import QRcode from 'qrcode';
import { dictionary } from '@/utils/dictMixin';
import { jsonToHump } from '@/utils/index';
import { notifyAction } from '@/utils';
import {
  findUrlQR,
  queryPrintData,
  getAdviceLabour,
  getAdvicePart,
  getRepairTypes,
  getLabourWorkData,
  getPartWorkData,
  queryRoLabourByRoNO,
  queryRoRepairPartByRoNO,
  queryRoAddItemByRoNO,
  queryCompanyInforById
} from '@/api/repair/repairReception/feesSettlement';

import { queryVipInfoByRono, queryVipInfoByBillNo } from '@/api/finance/repairFinance/cancelFinance';
import { getCompanyId } from '@/assets/js/auth';
import { getUser } from '@/assets/js/auth';
import { getList, getAllUser, getRoLabourByRoNOs } from '@/api/repair/repairReception/mergePrintfinance';
import { findAllRepair } from '@/api/repair/basicParameters';

export default {
  name: 'CardType',
  components: {},
  mixins: [dictionary],
  data() {
    this.BaseTable = null;
    this.selectedRow = [];
    this.editData = {};
    return {
      printVehicledShow: false,
      topFilterList: this.createTopFilters(),
      columns: this.createTableColumns(),
      fetchApi: getList,
      printList: {}, // 结算单数据
      printExitCardList: {}, // 出门证数据
      userList: [], // 人员信息表
      fetchParams: {},
      actions: { visible: false, type: '', title: '' }, // 弹出面板的相关信息
      companyRes: {}
    };
  },
  created() {
    this.getAllUser();
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  methods: {
    createTopFilters() {
      return [
        {
          type: 'RANGE_DATE',
          label: '结算日期',
          fieldName: 'ERDAT_START|ERDAT_END'
        },
        {
          type: 'INPUT',
          label: '委托书编号',
          fieldName: 'roNo',
          placeholder: '请输入...'
        },
        {
          type: 'INPUT',
          label: '结算单号',
          fieldName: 'balanceNo',
          placeholder: '请输入...'
        }
        // {
        //   type: 'MULTIPLE_CHECKBOX',
        //   fieldName: 'showTax',
        //   itemList: [{ text: '显示税额', value: '1' }],
        //   change: this.checkBoxHandle
        // },
        // {
        //   type: 'MULTIPLE_CHECKBOX',
        //   fieldName: 'printVIP',
        //   itemList: [{ text: '打印会员信息', value: '1' }],
        //   change: this.checkBoxHandle
        // }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.$index + 1}</span>;
          }
        },
        {
          title: '接车服务顾问',
          dataIndex: 'SERVICE_ADVISOR',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{this.userList[props.row.SERVICE_ADVISOR]}</span>;
          }
        },
        {
          title: '委托书编号',
          dataIndex: 'RO_NO',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '维修类型',
          dataIndex: 'REPAIR_TYPE_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '客户代码',
          dataIndex: 'OWNER_NO',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '客户名称',
          dataIndex: 'OWNER_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: 'VIN',
          width: 150,
          dataIndex: 'VIN',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '牌照号',
          dataIndex: 'LICENSE',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number'
        },
        {
          title: '结算单号',
          dataIndex: 'BALANCE_NO',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '收银状态',
          dataIndex: 'PAY_OFF',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{props.row.PAY_OFF === 10041001 ? '结清' : '欠款'}</span>;
          }
        },
        {
          title: '结算日期',
          dataIndex: 'BALANCE_TIME',
          sorter: true,
          filter: true,
          dateFormat: 'yyyy-MM-dd',
          filterType: 'date-range'
        },
        {
          title: '合计金额',
          dataIndex: 'RECEIVEABLE_TOTAL_AMOUNT',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number'
        },
        {
          title: '合计优惠',
          dataIndex: 'PREFERENTIAL_AMOUNT',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '结算员',
          dataIndex: 'BALANCE_HANDLER',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{this.userList[props.row.BALANCE_HANDLER]}</span>;
          }
        },
        // {
        //   title: '包工方式',
        //   dataIndex: 'ZHBQK',
        //   sorter: true,
        //   filter: true,
        //   precision: 2,
        //   filterType: 'number'
        // },
        {
          title: '应收工时费',
          dataIndex: 'RECEIVEABLE_LABOUR_FEE',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number'
        },
        {
          title: '实收工时费',
          dataIndex: 'REAL_LABOUR_FEE',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number'
        },
        {
          title: '应收材料费',
          dataIndex: 'RECEIVEABLE_REPAIR_PART_FEE',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number'
        },
        {
          title: '实收材料费',
          dataIndex: 'REAL_REPAIR_PART_FEE',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number'
        },
        {
          title: '操作人',
          dataIndex: 'CREATED_BY',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{this.userList[props.row.CREATED_BY]}</span>;
          }
        }
      ];
    },
    printBalanceClick() {
      if (!this.selectedRow.length) {
        this.$notify.warning({ title: '提示信息', message: '请选择打印对象' });
      } else {
        this.getBalancePrintData();
      }
    },
    // 获取结算单打印数据
    async getBalancePrintData() {
      let roNoList = []; // 工单号
      let balanceNoList = []; // 结算单号
      let vinList = []; // vin码
      let repairTypeList = []; // 维修类型
      this.selectedRow.map(item => {
        roNoList.push(item.RO_NO);
        balanceNoList.push(item.BALANCE_NO);
        vinList.push(item.VIN);
        repairTypeList.push(item.REPAIR_TYPE_NAME);
      });
      let deWeightVinList = [...new Set(vinList)];
      let deWeightRepariList = [...new Set(repairTypeList)];

      if (deWeightVinList.length > 1) {
        return notifyAction('不同车辆不能合并打印', 'warning');
      }
      if (deWeightVinList.length > 1) {
        return notifyAction('维修类型不同不能合并打印', 'warning');
      }

      // 请求打印数据
      let totalData = '', // 获取工单信息及客户数据
        orderData = [], // 结算单详情
        companyData = '', // 根据公司id获取公司信息
        remarkParams = []; // 说明

      // 获取工单信息及客户数据
      try {
        totalData = await queryPrintData(this.selectedRow[0].RO_NO, this.selectedRow[0].BALANCE_NO);
      } catch (err) {
        console.log(err, '获取打印经销商与客户数据失败');
      }

      // 获取公司信息
      try {
        companyData = await queryCompanyInforById({
          owenrCode: getCompanyId()
        });
      } catch (err) {
        console.log(err, '获取公司信息失败');
      }

      // 获取结算单说明 8107 - 8112
      try {
        let remarkArr = ['8107', '8108', '8109', '8110', '8111', '8112'];
        let remarkRes = (await findAllRepair()).data;
        let arr = [];
        for (let item in remarkRes) {
          if (remarkArr.includes(item)) {
            arr.push(remarkRes[item]);
          }
        }
        remarkParams = arr;
      } catch (err) {
        console.log(err, '获取结算说明失败');
      }

      // 获取备件、项目以及金额数据
      try {
        // 拼接请求单号
        let roNosList = [];
        roNoList.map((item, index) => {
          roNosList.push(item + '&' + balanceNoList[index]);
        });
        let orderDataRes = await getRoLabourByRoNOs({ roNos: roNosList.join(',') });
        if (orderDataRes.resultCode == 200) {
          orderData = orderDataRes.data;
        }
      } catch (err) {
        console.log('获取备件，项目金额失败', err);
      }

      try {
        // 结算日期单独处理
        totalData && (totalData.data.roInfo.COMPLETE_TIME = totalData.data.roInfo.COMPLETE_TIME ? totalData.data.roInfo.COMPLETE_TIME.split('T')[0] : '');
        // 翻译部分数据
        totalData && (totalData.data.roInfo.TRACE_TIME = this.createDictText(totalData.data.roInfo.TRACE_TIME, '8029'));
        totalData.data.roInfo.SERVICE_ADVISOR = totalData.data.roInfo.SERVICE_ADVISOR ? this.userList[totalData.data.roInfo.SERVICE_ADVISOR] : '';
        orderData.map(item1 => {
          item1.labourList.map(item2 => {
            item2.LABOUR_PROPERTY = this.createDictText(item.LABOUR_PROPERTY, '8104');
          });
        });
      } catch (err) {
        console.log(err, '翻译部分数据失败');
      }

      this.printList = {
        ...totalData.data,
        companyData: companyData.data,
        remarkParams,
        orderData
      };

      // if (companyData.data && companyData.data.province == 320000) {
      //   // 江苏
      //   this.$refs.printJS.EXCUTE_PRINT();
      // } else if (companyData.data && companyData.data.province == 310000) {
      //   // 上海
      //   this.$refs.printSH.EXCUTE_PRINT();
      // } else {
      this.$refs.print.EXCUTE_PRINT();
      // }
    },
    // 打印出门证
    async printCard() {
      let companyData = ''; // 根据公司id获取公司信息
      if (!this.selectedRow.length) {
        this.$notify.warning({ title: '提示信息', message: '请选择打印对象' });
        return;
      } else {
        this.printVehicledShow = true;
        //  let balanceTime = moment(this.selectedRow.BALANCE_TIME).format('YYYY-MM-DD');
        // let roCreateDate = moment(this.selectedRow.RO_CREATE_DATE).format('YYYY-MM-DD');
        let balanceHandler = this.selectedRow[0].BALANCE_HANDLER;
        // let users = this.columns.find(x => x.dataIndex === 'BALANCE_HANDLER').editItems;
        // users.forEach(x => {
        //   if (x.value === balanceHandler) {
        //     balanceHandler = x.text;
        //   }
        // });
        // 获取公司信息
        try {
          companyData = await queryCompanyInforById({
            owenrCode: getCompanyId()
          });

          console.log(companyData);
        } catch (err) {
          console.log(err, '获取公司信息失败');
        }

        this.printExitCardList = {
          license: this.selectedRow[0].LICENSE,
          ownerName: this.selectedRow[0].OWNER_NAME,
          balanceHandler: getUser(),
          companyData: companyData.data
        };
        this.$nextTick(() => {
          this.$refs.printVehicled.EXCUTE_PRINT();
        });
      }
    },

    // 获取二维码改造
    async getPayQrcode(BALANCE_NO, OWNER_NO) {
      // 获取收费对象
      // let object = this.formList.find(item => item.fieldName === 'object').initialValue;
      // 判断收费对象是否与结算单收费对象一致一致则查询二维码
      // console.log(object, OWNER_NO, BALANCE_NO, BALANCE_NO);
      if (BALANCE_NO !== '' && BALANCE_NO !== undefined) {
        const res = await findUrlQR(OWNER_NO, BALANCE_NO);
        console.log(res, 'res');

        if (res.resultCode === 200) {
          let url = res.data.GOTO_URL;
          this.GOTO_URL = url;
          if (url !== undefined && url !== '') {
            const setUrl = await QRcode.toDataURL(url);
            return setUrl;
          }
        } else {
          throw new Error(res);
        }
      } else {
        throw new Error('收费对象与结算单收费对象不符');
      }
    },

    async getAllUser() {
      const res = await getAllUser();
      console.log('操作员、录入人', res);
      res.data.map(e => {
        this.userList[e.userId] = e.employeeName;
      });
      // this.topFilterList.find(item => item.fieldName === 'inputer').itemList = res.data.map(x => ({ value: x.userId, text: x.employeeName }));
    },
    changeHandler(val) {
      val.ERDAT_START = val.ERDAT_START ? val.ERDAT_START.split(' ')[0] + ' 00:00:00' : '';
      val.ERDAT_END = val.ERDAT_END ? val.ERDAT_END.split(' ')[0] + ' 23:59:59' : '';
      this.fetchParams = { ...val };
    },
    rowSelectHandle(rows) {
      if (!rows.length) return;
      this.selectedRow = rows;
    },

    // 主页面刷新
    refreshHandle() {
      this.fetchParams = { ...this.fetchParams };
    },

    // 适配 BaseTable 组件
    collapseHandle() {
      this.$nextTick(this.BaseTable.EXECUTE_RESET_HEIGHT);
    }
  }
};
</script>

<style lang="less" scoped></style>
